package com.naiterui.ehp.bs.recommend.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.naiterui.ehp.bp.bo.doctor.RecomDoctorBO;
import com.naiterui.ehp.bp.bo.doctor.RecomPatientBO;
import com.naiterui.ehp.bp.bo.doctor.RecomPatientBO.AgeUnitEunm;
import com.naiterui.ehp.bp.bo.doctor.RecomUserInfoBO;
import com.naiterui.ehp.bp.bo.patient.PatientInquirerBO;
import com.naiterui.ehp.bp.bo.pharmacist.PharmacistInfoBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.date.DateUtil;
import com.naiterui.ehp.bp.utils.esign.ESignUtils;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bp.utils.lang.StringUtil;
import com.naiterui.ehp.bs.recommend.bean.DrMedicationRecomDiagnosis;
import com.naiterui.ehp.bs.recommend.bean.DrMedicationRecomInfo;
import com.naiterui.ehp.bs.recommend.bean.MedicationRecom;
import com.naiterui.ehp.bs.recommend.bean.MedicationRecomDetail;
import com.naiterui.ehp.bs.recommend.bean.MedicationRequire;
import com.naiterui.ehp.bs.recommend.exception.ExceptionCodes;
import com.naiterui.ehp.bs.recommend.remote.IDoctorFeignClient;
import com.naiterui.ehp.bs.recommend.remote.IEsignFeignClient;
import com.naiterui.ehp.bs.recommend.remote.IPatientFeignClient;
import com.naiterui.ehp.bs.recommend.remote.IPharmacistFeignClient;
import com.naiterui.ehp.bs.recommend.remote.IRecommendRemoter;
import com.naiterui.ehp.bs.recommend.repository.mysql.IMedicationRecomDetailRepository;
import com.naiterui.ehp.bs.recommend.repository.mysql.IMedicationRecomDiagnosisRepository;
import com.naiterui.ehp.bs.recommend.repository.mysql.IMedicationRecomInfoRepository;
import com.naiterui.ehp.bs.recommend.repository.mysql.IMedicationRecomRepository;
import com.naiterui.ehp.bs.recommend.repository.mysql.IMedicationRequireRepository;
import com.naiterui.ehp.bs.recommend.service.IESignService;
import com.naiterui.ehp.bs.recommend.service.IPrescriptionService;
import com.naiterui.ehp.bs.recommend.service.IRecomCreaterService;
import com.naiterui.ehp.bs.recommend.util.Constants;
import com.naiterui.ehp.bs.recommend.util.SerialNumberUtil;
import com.naiterui.ehp.bs.recommend.vo.MedicationBoxVO;
import com.naiterui.ehp.bs.recommend.vo.prescription.PatientPrescriptionVO;
import com.naiterui.ehp.bs.recommend.vo.prescription.PrescriptionDetailVO;
import com.naiterui.ehp.bs.recommend.vo.prescription.PrescriptionItemVO;
import com.naiterui.ehp.bs.recommend.vo.prescription.PrescriptionVO;

@Service
public class PrescriptionServiceImpl implements IPrescriptionService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PrescriptionServiceImpl.class);

    @Autowired
    private IRecommendRemoter remoter;
    @Autowired
    private IMedicationRecomRepository medicationRecomRepository;
    @Autowired
    private IMedicationRecomDetailRepository medicationRecomDetailRepository;
    @Autowired
    private IMedicationRecomInfoRepository medicationRecomInfoRepository;
    @Autowired
    private IRecomCreaterService recomCreaterService;
    @Autowired
    private IESignService signService;
    @Autowired
    private IMedicationRecomDiagnosisRepository medicationRecomDiagnosisRepository;
    @Autowired
    private IPharmacistFeignClient pharmacistFeignClient;

    @Autowired
    private IEsignFeignClient esignFeignClient;

    @Autowired
    private IPatientFeignClient patientFeignClient;
    @Autowired
    private IMedicationRequireRepository medicationRequireRepository;

    @Autowired
    private IDoctorFeignClient doctorFeignClient;

    public static final String HOSPITAL_NAME = ConfigUtil.getString("ehp.hospital.name");

    // 处方笺药师默认文案
    private static final String PRESCRIPTION_PHARMACISTNAME = ConfigUtil.getString("prescription.pharmacistname");
    // 历史处方笺抬头
    private static final String PRESCRIPTION_HISTORY_TITLE = ConfigUtil.getString("prescription.history.title");

    private static final String PRESCRIPTION_POSTFIX = "处方笺";
    public static final String SIGNATURE_POSTFIX = "专用章";


    @Override
    public PrescriptionVO getPrescription(Long doctorId, Long patientId, Long inquirerId) throws BusinessException {
        PrescriptionVO prescriptionVO = new PrescriptionVO();
        prescriptionVO.setPatientId(patientId);
        prescriptionVO.setTitle(HOSPITAL_NAME + PRESCRIPTION_POSTFIX);

        // 推药次数(用药+申请)
        long recomCount = medicationRecomRepository.getRecomCount(doctorId, patientId);
        // 推荐过用药/申请单，才获取患者昵称，否则不获取患者昵称
        boolean fetchNickname = recomCount > 0;
        // 用户信息
        RecomUserInfoBO userInfo = remoter.getUserInfo(doctorId, patientId, fetchNickname);
        RecomDoctorBO doctor = userInfo.getDoctor();
        RecomPatientBO patient = userInfo.getPatient();
        if (doctor == null || patient == null) {
            LOGGER.info("医生或患者信息不存在");
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }

        prescriptionVO.setDoctorName(doctor.getName());
        //所有科室只显示一级科室——【医生端V3.4.0-by gongbaoqiang】
        String departmemntName = recomCreaterService.getDepartmentName(userInfo);
        prescriptionVO.setDepartmentName(departmemntName);
        Integer status = patient.getStatus();
        //获取就诊人信息
        List<PatientInquirerBO> inquirerBOS = patientFeignClient.getPatientInquirer(Lists.newArrayList(inquirerId));
        if (CollectionUtils.isEmpty(inquirerBOS)) {
            LOGGER.error("就诊人信息不存在：inquirerId={}", inquirerId);
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }
        PatientInquirerBO inquirer = inquirerBOS.get(0);
        prescriptionVO.setPatientName(inquirer.getName());
        prescriptionVO.setPatientAge(inquirer.getAgeYear());
        prescriptionVO.setPatientAgeUnit("岁");
        prescriptionVO.setPatientAgeStr(inquirer.getAge());
        prescriptionVO.setPatientGender(inquirer.getGender());
        prescriptionVO.setRelation(inquirer.getRelation());
        prescriptionVO.setRelationName(inquirer.getRelationName());

        // 默认的处方单编号格式
        prescriptionVO.setSerialNumber(SerialNumberUtil.getRecomDefaultNum(doctor.getDepartmentId()));
        prescriptionVO.setRecomTime(System.currentTimeMillis());
        // 处方有效期描述
        prescriptionVO.setExpireDesc(ConfigUtil.getString("prescription.expire.desc"));
        // 药师描述
        prescriptionVO.setPharmacistName(PRESCRIPTION_PHARMACISTNAME);
        prescriptionVO.setInquirerId(inquirerId);
        return prescriptionVO;
    }


    @Override
    public PrescriptionDetailVO getPrescriptionDetailForDoctor(Long doctorId, Long patientId, Long recommendId, Boolean showExpire)
        throws BusinessException {
        PrescriptionDetailVO prescriptionDetailVO = new PrescriptionDetailVO();
        getPrescriptionDetail(prescriptionDetailVO, doctorId, patientId, recommendId, false);
        return prescriptionDetailVO;
    }

    @Override
    public PatientPrescriptionVO getPrescriptionDetailForPatient(Long doctorId, Long patientId, Long recommendId) throws BusinessException {
        PrescriptionDetailVO prescriptionDetailVO = new PatientPrescriptionVO();

        // 患者端接口不传doctorId
        getPrescriptionDetail(prescriptionDetailVO, doctorId, patientId, recommendId, true);
        PatientPrescriptionVO patientPrescriptionVO = (PatientPrescriptionVO) prescriptionDetailVO;

        // 查询医生付费状态
        Integer status = remoter.getDrConsultChargeStatus(patientPrescriptionVO.getDoctorId(), patientId);
        patientPrescriptionVO.setChargeStatus(status);
        return patientPrescriptionVO;
    }

    private void getPrescriptionDetail(PrescriptionDetailVO prescriptionDetail, Long doctorId, Long patientId, Long recommendId, boolean fromPatient)
        throws BusinessException {
        /*
         *  推荐单主信息
         */
        MedicationRecom medicationRecom = medicationRecomRepository.get(recommendId);
        if (medicationRecom == null) {
            LOGGER.info("推荐单不存在：{}", recommendId);
            throw new BusinessException(ExceptionCodes.RECOM_NOT_EXIST);
        }

        // 查询诊断列表
        List<DrMedicationRecomDiagnosis> diagnoses = medicationRecomDiagnosisRepository.findByRecommendId(recommendId);
        List<String> diagnosesList = diagnoses.stream().map(DrMedicationRecomDiagnosis::getName).collect(Collectors.toList());
        prescriptionDetail.setDiagnosisList(diagnosesList);

        // 患者端不传医生ID，由推荐记录赋值
        if (fromPatient) {
            // 查询该推荐单的申请购药时间是否小于3个小时，小于3小时不能再次申请购药
            Date lastRequireDate = medicationRecom.getLastRequireAt();
            if (lastRequireDate == null) {
                ((PatientPrescriptionVO) prescriptionDetail).setCanRequire(Constants.STATUS_YES);
            } else {
                Date twoHourAfter = DateUtil.addMinutes(lastRequireDate, ConfigUtil.getInt("prescription.requier.interval"));
                Date now = new Date();
                if (now.after(twoHourAfter)) {
                    ((PatientPrescriptionVO) prescriptionDetail).setCanRequire(Constants.STATUS_YES);
                } else {
                    ((PatientPrescriptionVO) prescriptionDetail).setCanRequire(Constants.STATUS_NO);
                }
            }
            doctorId = medicationRecom.getDoctorId();
            patientId = patientId == null ? medicationRecom.getPatientId() : patientId;
        }

        // 推荐单编号
        prescriptionDetail.setSerialNumber(medicationRecom.getSerialNumber());
        // 推荐时间
        prescriptionDetail.setRecomTime(medicationRecom.getCreatedAt().getTime());
        // 诊断
        prescriptionDetail.setDiagnosis(medicationRecom.getDiagnosis());
        prescriptionDetail.setRecommendId(recommendId);

        // 是否已购,新加了状态，需要判断如果为0，则可购买，其他情况为未购
        Integer buyStatus = Constants.RecomStatusEunm.NOT_BUY.getCode();
        if (medicationRecom.getStatus() != null && (MedicationRecom.RECOM_STATUS_HAS_BUY.equals(medicationRecom.getStatus())
            || MedicationRecom.RECOM_STATUS_ORDERD.equals(medicationRecom.getStatus())
            || MedicationRecom.RECOM_STATUS_CANCEL.equals(medicationRecom.getStatus()))){
            buyStatus = Constants.RecomStatusEunm.ALREADY_BUY.getCode();
        }
        prescriptionDetail.setBuy(buyStatus);
        // 是否已过期,历史数据以实际的为准
        Date expireAt = medicationRecom.getExpireAt();
        int expireStatus = Constants.STATUS_NO;
        if (expireAt != null && expireAt.before(new Date())) {
            expireStatus = Constants.STATUS_YES;
        }
        prescriptionDetail.setExpire(expireStatus);
        // 如果是已购买 或者 已过期，则不可再次购买——原失效逻辑
        if (buyStatus == Constants.RecomStatusEunm.ALREADY_BUY.getCode() || expireStatus == Constants.STATUS_YES) {
            prescriptionDetail.setCanBuy(Constants.STATUS_NO);
        } else {
            prescriptionDetail.setCanBuy(Constants.STATUS_YES);
        }

        //返回作废状态和作废时间，医生端V3.4.0——by gongbaoqiang
        prescriptionDetail.setInvalid(medicationRecom.getInvalid());
        if (medicationRecom.getInvalidAt() != null) {
            prescriptionDetail.setInvalidTime(medicationRecom.getInvalidAt());
        }
        Integer showInvalidBtn = Constants.SHOW_INVALID_BTN_YES;
        //设置作废按钮是否显示：已成单（后）、已失效、已作废均不显示
        if (buyStatus != Constants.RecomStatusEunm.NOT_BUY.getCode()) {
            showInvalidBtn = Constants.SHOW_INVALID_BTN_NO;
        } else if (expireStatus == Constants.STATUS_YES) {
            showInvalidBtn = Constants.SHOW_INVALID_BTN_NO;
        } else if (medicationRecom.getInvalid() != null && medicationRecom.getInvalid() == MedicationRecom.INVALID_YES) {
            showInvalidBtn = Constants.SHOW_INVALID_BTN_NO;
        }
        prescriptionDetail.setShowInvalidBtn(showInvalidBtn);

        /*
         *  药品信息
         */
        List<MedicationRecomDetail> medicationRecomDetail = medicationRecomDetailRepository.findByRecommendId(recommendId);
        if (medicationRecomDetail == null || medicationRecomDetail.size() <= 0) {
            LOGGER.info("推荐单商品列表为空：{}", recommendId);
            throw new BusinessException(ExceptionCodes.DOCTOR_RECOM_ITEMS_NULL);
        }

        prescriptionDetail.setDoctorId(doctorId);
        // 获取药品价格列表

        List<PrescriptionItemVO> items = new ArrayList<>();
        copyRecomDetail(medicationRecomDetail, items);
        prescriptionDetail.setItems(items);

        /*
         *  推荐单处方信息
         */
        DrMedicationRecomInfo recomInfo = medicationRecomInfoRepository.findFirstByRecommendId(recommendId);

        // 历史处方
        if (recomInfo == null) {
            LOGGER.info("历史处方");
            handleOldPrescription(doctorId, patientId, prescriptionDetail);
        }
        // 新处方
        else {
            LOGGER.info("新处方");
            handleNewPrescription(recomInfo, prescriptionDetail);
        }
        // 患者端过期提醒方案
        if (fromPatient) {
            String desc;
            if (buyStatus == Constants.RecomStatusEunm.ALREADY_BUY.getCode() && expireStatus == Constants.STATUS_NO) {
                //已经购买过的处方且处方未过期，点击按钮“重新申请购买”时 的提示信息
                desc = ConfigUtil.getString("prescription.patient.buy.desc");
            } else {
                // 重新购买已经过期的处方，初次点击按钮“重新申请购买”时 或 已经购买过的处方且处方过期 提示信息
                desc = ConfigUtil.getString("prescription.expire.patient.desc");
            }
            prescriptionDetail.setExpireDesc(desc);
        }

        prescriptionDetail.setCheckingStatus(recomInfo.getCheckingStatus());
        prescriptionDetail.setCheckingDesc(recomInfo.getCheckingDesc());
        // 手写/方章
        prescriptionDetail.setHandWriting(ESignUtils.isHandWriting() ? Constants.STATUS_YES : Constants.STATUS_NO);
        // 是否已求药
        MedicationRequire medicationRequire = medicationRequireRepository.findFirstByFormerRecommendId(medicationRecom.getId());
        Integer require = Constants.STATUS_NO;
        if (null != medicationRequire) {
            require = Constants.STATUS_YES;
        }
        prescriptionDetail.setRequire(require);
        //详情增加status字段，使列表和详情状态判断条件一致
        prescriptionDetail.setStatus(medicationRecom.getStatus());
    }

    /**
     * 历史处方显示处理
     *
     * @param doctorId           医生ID
     * @param patientId          患者ID
     * @param prescriptionDetail 返回VO
     * @throws BusinessException
     * @Description
     * @author wangchuan
     * @Date 2017年7月28日
     * @since V2.9.0
     */
    private void handleOldPrescription(Long doctorId, Long patientId, PrescriptionDetailVO prescriptionDetail) throws BusinessException {
        // 抬头统一显示
        prescriptionDetail.setTitle(PRESCRIPTION_HISTORY_TITLE);
        RecomUserInfoBO userInfo = remoter.getUserInfo(doctorId, patientId);
        //RecomDoctorBO doctor = userInfo.getDoctor();
        RecomDoctorBO doctor = doctorFeignClient.getRecomDoctorInfo(doctorId);
        RecomPatientBO patient = userInfo.getPatient();
        if (doctor == null || patient == null) {
            LOGGER.info("医生或患者信息不存在。doctorId={}, patientId={}", doctorId, patientId);
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }

        /*
         * 由医生服务提供信息
         */
        prescriptionDetail.setDoctorName(doctor.getName());
        prescriptionDetail.setDepartmentName(doctor.getDepartmentName());

        String patientName = patient.getName();
        prescriptionDetail.setPatientName(patientName == null ? "" : patientName);
        prescriptionDetail.setPatientAge(patient.getAge());
        if (patient.getAge() != null && patient.getAge() != 0) {
            prescriptionDetail.setPatientAgeUnit(AgeUnitEunm.YEAR.getUnit());
        }
        prescriptionDetail.setPatientGender(patient.getGender());

        // 处方有效期不显示
        prescriptionDetail.setExpireDesc("");
        // 慢性病描述不显示
        prescriptionDetail.setChronicDisease("");
        // 药师不显示
        prescriptionDetail.setPharmacistName("");
        // 签章不显示
        prescriptionDetail.setShowDoctorSignature(PrescriptionDetailVO.SHOW_SIGNATURE_FALSE);
        prescriptionDetail.setShowPharmacistSignature(PrescriptionDetailVO.SHOW_SIGNATURE_FALSE);

        //返回核对发药人为空
        prescriptionDetail.setCheckMedicationName("");
        // 处理处方价格
        handlePrescriptionPrice(doctor, prescriptionDetail);
    }

    /**
     * 新处方显示处理
     * @param recomInfo
     * @param prescriptionDetail
     * @throws BusinessException
     */
    private void handleNewPrescription(DrMedicationRecomInfo recomInfo, PrescriptionDetailVO prescriptionDetail) throws BusinessException {
        // 备案医院ID
        Integer recordHospitalId = recomInfo.getRecordHospitalId();
        // 备案医院名
        prescriptionDetail.setTitle(HOSPITAL_NAME + PRESCRIPTION_POSTFIX);
        /*
         * 由医生服务提供信息
         */
        prescriptionDetail.setDoctorName(recomInfo.getDoctorName());
        prescriptionDetail.setDepartmentName(recomInfo.getDepartmentName());
        prescriptionDetail.setInquirerId(recomInfo.getInquirerId());
        prescriptionDetail.setPatientName(recomInfo.getPatientName());
        prescriptionDetail.setPatientAge(recomInfo.getPatientAge());
        String ageUnit = AgeUnitEunm.YEAR.getUnit();// 默认年龄单位为岁
        if (StringUtils.isNotEmpty(recomInfo.getPatientAgeUnit())) {
            ageUnit = recomInfo.getPatientAgeUnit();
        }
        prescriptionDetail.setPatientAgeUnit(ageUnit);
        prescriptionDetail.setPatientGender(recomInfo.getPatientGender());
        prescriptionDetail.setPatientAgeStr(recomInfo.getPatientAgeStr());

        // 处方有效期
        prescriptionDetail.setExpireDesc(ConfigUtil.getString("prescription.expire.desc"));
        // 慢性病描述
        prescriptionDetail.setChronicDisease(recomInfo.getTips());

        prescriptionDetail.setPrePharmacistName(recomInfo.getPrePharmacistName());
        // 药师姓名
        prescriptionDetail.setPharmacistName(recomInfo.getPharmacistName());
        // 调配药师姓名
        prescriptionDetail.setAlPharmacistName(recomInfo.getAllocatePharmacistName());

        //RecomUserInfoBO userInfo = remoter.getUserInfo(recomInfo.getDoctorId(), null);
        RecomDoctorBO doctor = doctorFeignClient.getRecomDoctorInfo(recomInfo.getDoctorId());

        // 医生签名状态
        Integer doctorSignStatus = recomInfo.getDoctorSignStatus();
        // 医生是否已签名
        boolean doctorSignDone = doctorSignStatus != null && DrMedicationRecomInfo.DOCTOR_SIGN_STATUS_DONE == doctorSignStatus;
        // 是否显示医生签章
        prescriptionDetail.setShowDoctorSignature(doctorSignDone ? PrescriptionDetailVO.SHOW_SIGNATURE_TRUE : PrescriptionDetailVO.SHOW_SIGNATURE_FALSE);
        if (doctorSignDone) {
            if (recomInfo.getDoctorSignTime() != null) {
                prescriptionDetail.setDoctorAuditTime(recomInfo.getDoctorSignTime().getTime());
                //医师签章地址
                // EsignDoctorBO esignDoctorBO = esignFeignClient.getDrEsignInfo(recomInfo.getDoctorId());
                // prescriptionDetail.setDrSealImage(esignDoctorBO.getSealImage());
                // 取用户上传的签章
                prescriptionDetail.setDrSealImage(doctor.getSealImage());
            }
        }

        // 药师签名状态
        Integer pharmacistSignStatus = recomInfo.getPharmacistSignStatus();
        // 药师是否已签名
        boolean pharmacistSignDone = pharmacistSignStatus != null && DrMedicationRecomInfo.PHARMACIST_SIGN_STATUS_DONE == pharmacistSignStatus;
        // 是否显示药师签章
        prescriptionDetail.setShowPharmacistSignature(pharmacistSignDone ? PrescriptionDetailVO.SHOW_SIGNATURE_TRUE : PrescriptionDetailVO.SHOW_SIGNATURE_FALSE);
        if (pharmacistSignDone) {
            if (recomInfo.getPharmacistSignTime() != null && recomInfo.getPharmacistId() != null) {
                LOGGER.info("处方及药师信息：recomId={}, pharmacistId={}", recomInfo.getRecommendId(), recomInfo.getPharmacistId());
                // 药师信息
                PharmacistInfoBO pharmacistInfo = pharmacistFeignClient.getPharmacistInfo(recomInfo.getPharmacistId());
                // 药师审核时间
                prescriptionDetail.setPharmacistAuditTime(recomInfo.getPharmacistSignTime().getTime());
                //药师签章地址
                // EsignPharmacistBO esignPharmacistBO = esignFeignClient.getPhEsignInfo(recomInfo.getPharmacistId());
                // prescriptionDetail.setPhSealImage(esignPharmacistBO.getSealImage());
                // 取用户上传的签章
                prescriptionDetail.setPhSealImage(pharmacistInfo.getSealImage());
            }
        }

        // 调配药师签名状态
        Integer allocatePharmacistSignStatus = recomInfo.getAllocatePharmacistSignStatus();
        // 调配药师是否已签名
        boolean alPharmacistSignDone = allocatePharmacistSignStatus != null && DrMedicationRecomInfo.AL_PHARMACIST_SIGN_STATUS_DONE == allocatePharmacistSignStatus;
        // 是否显示调配药师签章
        prescriptionDetail.setShowAlPharmacistSignature(alPharmacistSignDone ? PrescriptionDetailVO.SHOW_SIGNATURE_TRUE : PrescriptionDetailVO.SHOW_SIGNATURE_FALSE);
        if (alPharmacistSignDone) {
            if (recomInfo.getAllocatePharmacistSignTime() != null && recomInfo.getAllocatePharmacistId() != null) {
                LOGGER.info("处方及调配药师信息：recomId={}, pharmacistId={}", recomInfo.getRecommendId(), recomInfo.getAllocatePharmacistId());
                // 调配药师信息
                PharmacistInfoBO pharmacistInfo = pharmacistFeignClient.getPharmacistInfo(recomInfo.getAllocatePharmacistId());
                // 药师审核时间
                prescriptionDetail.setAlPharmacistAuditTime(recomInfo.getAllocatePharmacistSignTime().getTime());
                //调试药师签章地址
                prescriptionDetail.setAlPhSealImage(pharmacistInfo.getSealImage());
            }
        }

        //返回核对发药数据
        prescriptionDetail.setCheckMedicationName(recomInfo.getCheckMedicationName() == null ? "" : recomInfo
            .getCheckMedicationName());

        // 医生和药师签章名相同，任意一个需要签章，返回签章名
        if (doctorSignDone || pharmacistSignDone) {
            // 签章名称信息
            prescriptionDetail.setSignatureContent(HOSPITAL_NAME + SIGNATURE_POSTFIX);
        }

        // 处理处方价格
        //RecomDoctorBO doctor = userInfo.getDoctor();
        if (doctor == null) {
            LOGGER.info("医生信息不存在。doctorId={}", recomInfo.getDoctorId());
            throw new BusinessException(ExceptionCodes.USER_NOT_EXIST);
        }
        handlePrescriptionPrice(doctor, prescriptionDetail);
    }

    /**
     * 推荐单中商品列表属性复制
     *
     * @param source
     * @param target
     * @Description
     * @author wangchuan
     * @Date 2017年7月28日
     * @since V2.9.0
     */
    private void copyRecomDetail(List<MedicationRecomDetail> source, List<PrescriptionItemVO> target) {
        for (MedicationRecomDetail detail : source) {
            PrescriptionItemVO item = new PrescriptionItemVO();
            item.setPid(detail.getPid());
            item.setSkuId(detail.getSkuId());
            //默认取合规化名称，兼容老数据无合规化名称——医生端V3.4.1新增- by gongbaoqiang 2018-11-08
            // item.setName((detail.getRecomName() == null ? detail.getName() :
            // detail.getRecomName()).replaceAll("null", ""));
            item.setName(detail.getName());
            item.setCommonName(detail.getCommonName());
            item.setQuantity(detail.getQuantity());
            item.setUsages(detail.getUsages());
            // 字段名不一致，历史遗留问题
            item.setBackup(detail.getBakup());
            // 设置用法用量明细
            item.setDosageCycle(detail.getDosageCycle());
            item.setDosageCycleUnit(detail.getDosageCycleUnit());
            item.setDosageCount(detail.getDosageCount());
            item.setEachDosageCount(detail.getEachDosageCount());
            item.setEachDoseUnit(detail.getEachDoseUnit());
            item.setDrugCycle(item.getDrugCycle());
            item.setDrugCycleUnit(detail.getDrugCycleUnit());
            item.setQuantityUnit(detail.getQuantityUnit());
            item.setUsageMethod(detail.getUsageMethod());
            item.setUsageTime(detail.getUsageTime());
            boolean containUsageDetail = false;
            if (detail.getUsageTime() != null && detail.getDosageCount() != null) {
                containUsageDetail = true;
            }
            item.setContainUsageDetail(containUsageDetail);
            target.add(item);
        }
    }

    /**
     * 处理处方价格 PrescriptionServiceImpl.handlePrescriptionPrice()
     * @param doctorInfo
     * @param prescriptionDetail
     * @throws BusinessException
     */
    private void handlePrescriptionPrice(RecomDoctorBO doctorInfo, PrescriptionDetailVO prescriptionDetail) throws BusinessException {
        List<PrescriptionItemVO> itemVOList = prescriptionDetail.getItems();
        if (CollectionUtils.isNotEmpty(itemVOList)) {
            List<Long> pidList = new ArrayList<>();
            for (PrescriptionItemVO itemVO : itemVOList) {
                //pidList.add(itemVO.getPid());
                pidList.add(itemVO.getSkuId());
            }

            if (doctorInfo == null) {
                throw new BusinessException(ExceptionCodes.DOCTOR_NOT_EXIST);
            }

            // 医生所在区域Id
            Integer cityId = doctorInfo.getPriceCityId();
            // 指数显示方式 :0不显示 、1小七指数、2市场积分
            List<MedicationBoxVO> medicationBoxVOList = remoter.getMedicationList(doctorInfo.getId(), cityId, pidList, false);
            HashMap<Long, String> priceMap = new HashMap<>();
            for (MedicationBoxVO medicationBoxVO : medicationBoxVOList) {
                priceMap.put(medicationBoxVO.getSkuId(), medicationBoxVO.getSalePrice());
            }
            BigDecimal totalPriceDecimal = BigDecimal.ZERO;
            BigDecimal priceDecimal;
            BigDecimal countDecimal;
            for (PrescriptionItemVO itemVO : itemVOList) {
                String priceStr = priceMap.get(itemVO.getSkuId());
                if (StringUtils.isNotEmpty(priceStr)) {
                    itemVO.setSalePrice(priceStr);
                    priceDecimal = new BigDecimal(priceStr);
                    countDecimal = new BigDecimal(itemVO.getQuantity());
                    priceDecimal = priceDecimal.multiply(countDecimal);
                    totalPriceDecimal = totalPriceDecimal.add(priceDecimal);
                }
            }
            prescriptionDetail.setTotalPrice(StringUtil.formatFen2YuanStr(totalPriceDecimal.intValue()));
        }


    }
}
